package com.cjh.jwt;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

public class Test {

    //有效期
    private static final long TIME=1000*60*60*24;
    //签名
    private static final String SIGNATURE="admin";

    //生成token
    public static String getToken(){
        JwtBuilder jwtBuilder = Jwts.builder();
        String token=jwtBuilder
                //设置header（头部）
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                //设置payload（有效载荷）
                .claim("username","CJH")
                .setSubject("hello jwt")
                .setExpiration(new Date(System.currentTimeMillis()+TIME))
                .setId(UUID.randomUUID().toString())
                //设置signature（签名）
                .signWith(SignatureAlgorithm.HS256,SIGNATURE)
                .compact();
        System.out.println(token);
        return token;
    }

    //解析token
    public static void analysisToken(String token){
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(SIGNATURE).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        System.out.println(claims.get("username"));
        System.out.println(claims.getId());
        System.out.println(claims.getSubject());
        System.out.println(claims.getExpiration());
    }

    public static void main(String[] args)  {

        String token = getToken();
        System.out.println("解析token：");
        analysisToken(token);
    }
}
